package maa.action.admin;

import maa.action.Action;
import maa.action.ActionException;
import maa.action.ActionResult;
import maa.dao.*;
import maa.database.ConnectionPool;
import maa.entity.Log;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

public class ShowLog implements Action {
    @Override
    public ActionResult execute(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        ConnectionPool connectionPool = ConnectionPool.getInstance();
        DAOManager daoManager = DAOFactory.createDAOManager(connectionPool.getConnection());
        final List<Log> logs = new ArrayList<>();
        final DAOCommand daoCommand = new DAOCommand() {
            @Override
            public Object execute(DAOManager daoManager) throws ActionException {
                int amount = 0;
                try {
                    LogDAO logDAO = daoManager.getLogDAO();
                    amount = logDAO.amount();
                } catch (DAOException e) {
                    throw new ActionException("Exception in logDAO.amount()");
                }
                return amount;
            }
        };
        int amount = (int) daoManager.executeAndClose(daoCommand);
        int pages = (amount + 9) / 10;
        int page = 1;
        if (req.getParameter("page") != null) page = Integer.parseInt(req.getParameter("page"));
        daoManager.setConnection(connectionPool.getConnection());
        final int finalPageNumber = page;

        DAOCommand command = new DAOCommand() {
            @Override
            public Object execute(DAOManager daoManager) throws ActionException {
                List<Log> temp = null;
                try {
                    temp = daoManager.getLogDAO().find(10, finalPageNumber);
                } catch (DAOException e) {
                    throw new ActionException("Exception in logDAO.find()");
                }
                logs.addAll(temp);
                return logs;
            }
        };
        daoManager.executeAndClose(command);

        req.setAttribute("page", page);
        req.setAttribute("logs", logs);
        req.setAttribute("pages", pages);
        return new ActionResult("show-log");
    }
}
